<template>
	<view class="container">
		<!-- 商品信息 -->
		<view class="tui-order-item">
			<tui-list-cell padding="20rpx 30rpx" :hover="false" lineLeft="0">
				<view class="tui-goods-title"><view>商品信息</view></view>
			</tui-list-cell>
			<tui-list-cell padding="0" v-if="orderItem">
				<view class="tui-goods-item">
					<image :src="orderItem.picUrl" class="tui-goods-img" mode="aspectFill"></image>
					<view class="tui-goods-center">
						<view class="tui-goods-name">{{ orderItem.spuName }}</view>
						<view class="tui-goods-attr">
							<span v-for="(property, index) in orderItem.properties" :key="index">
								{{ property.propertyName }}: {{ property.valueName }}
								<span v-if="index < orderItem.properties.length - 1">, </span>
							</span>
						</view>
					</view>
					<view class="tui-price-right">
						<view class="tui-price">￥{{ fen2yuan(orderItem.payPrice) }}</view>
						<view class="tui-count">x{{ orderItem.count }}</view>
					</view>
				</view>
			</tui-list-cell>
		</view>

		<!-- 申请表单 -->
		<view class="tui-refund__form">
			<!-- 申请类型 -->
			<tui-list-cell :hover="false" padding="0">
				<view class="tui-line-cell">
					<view class="tui-title">
						<text class="tui-color__red">*</text>
						<text>申请类型</text>
					</view>
					<radio-group @change="onRefundTypeChange" class="tui-radio-group">
						<label class="tui-radio-item" v-for="(type, index) in refundTypes" :key="index">
							<radio 
								:value="type.value" 
								:checked="formData.way === type.value" 
								color="#E41F19"
								:disabled="type.disabled"
							/>
							<text class="tui-radio-text">{{ type.label }}</text>
						</label>
					</radio-group>
				</view>
			</tui-list-cell>

			<!-- 申请原因 -->
			<tui-list-cell padding="0" arrow @click="showReasonModal = true">
				<view class="tui-line-cell">
					<view class="tui-title">
						<text class="tui-color__red">*</text>
						<text>申请原因</text>
					</view>
					<view class="tui-input">
						<text v-if="formData.applyReason" class="tui-selected-text">{{ formData.applyReason }}</text>
						<text v-else class="tui-placeholder">请选择退款原因</text>
					</view>
				</view>
			</tui-list-cell>

			<!-- 退款金额 -->
			<tui-list-cell :hover="false" padding="0">
				<view class="tui-line-cell">
					<view class="tui-title">
						<text class="tui-color__red">*</text>
						<text>退款金额</text>
					</view>
					<view class="tui-input">
						<text class="tui-amount-text">￥{{ fen2yuan(refundAmount) }}</text>
					</view>
				</view>
			</tui-list-cell>

			<!-- 申请说明 -->
			<tui-list-cell :hover="false" padding="0">
				<view class="tui-line-cell tui-line-cell-textarea">
					<view class="tui-title">
						<text>申请说明</text>
					</view>
					<textarea 
						v-model="formData.applyDescription" 
						placeholder="请填写申请说明（选填）"
						class="tui-textarea"
						maxlength="200"
						:auto-height="true"
					></textarea>
				</view>
			</tui-list-cell>
		</view>

		<!-- 提交按钮 -->
		<view class="tui-btn__box">
			<tui-button 
				height="88rpx" 
				type="danger" 
				shadow 
				shape="circle"
				@click="submitRefund"
				:loading="submitting"
			>
				提交申请
			</tui-button>
		</view>

		<!-- 申请原因选择弹窗 -->
		<tui-bottom-popup :show="showReasonModal" @close="showReasonModal = false">
			<view class="tui-modal-box">
				<view class="tui-modal-header">
					<text class="tui-modal-title">申请原因</text>
					<text class="tui-modal-close" @click="showReasonModal = false">×</text>
				</view>
				<view class="tui-modal-content">
					<radio-group @change="onReasonChange">
						<label 
							class="tui-reason-item" 
							v-for="(reason, index) in currentReasonList" 
							:key="index"
						>
							<view class="tui-reason-text">{{ reason }}</view>
							<radio 
								:value="reason" 
								:checked="formData.applyReason === reason" 
								color="#E41F19"
							/>
						</label>
					</radio-group>
				</view>
				<view class="tui-modal-footer">
					<tui-button 
						type="black" 
						plain 
						width="200rpx" 
						height="70rpx" 
						:size="28" 
						shape="circle"
						@click="showReasonModal = false"
					>
						取消
					</tui-button>
					<tui-button 
						type="danger" 
						width="200rpx" 
						height="70rpx" 
						:size="28" 
						shape="circle"
						@click="confirmReason"
					>
						确定
					</tui-button>
				</view>
			</view>
		</tui-bottom-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			orderId: null,
			orderItemId: null,
			orderItem: null,
			orderInfo: null,
			formData: {
				way: '20', // 默认退款退货，10-仅退款，20-退款退货
				applyReason: '',
				applyDescription: '',
				images: []
			},
			refundTypes: [
				{ label: '仅退款', value: '10' },
				{ label: '退款退货', value: '20' }
			],
			refundReasons: [], // 仅退款原因列表
			returnReasons: [], // 退款退货原因列表
			currentReasonList: [], // 当前显示的原因列表
			showReasonModal: false,
			selectedReason: '', // 临时选中的原因
			submitting: false,
			tradeConfig: null // 交易配置
		};
	},
	computed: {
		// 计算退款金额
		refundAmount() {
			if (this.orderItem) {
				return this.orderItem.payPrice || 0;
			}
			return 0;
		}
	},
	onLoad(options) {
		// 获取传递的参数
		if (options.orderId) {
			this.orderId = options.orderId;
		}
		if (options.orderItemId) {
			this.orderItemId = parseInt(options.orderItemId);
		}

		if (!this.orderId || !this.orderItemId) {
			uni.showToast({
				title: '缺少订单信息',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
			return;
		}

		// 加载数据
		this.loadData();
	},
	methods: {
		// 加载数据
		async loadData() {
			// 加载订单详情
			await this.loadOrderDetail();
			// 加载交易配置
			await this.loadTradeConfig();
		},
		// 加载订单详情
		async loadOrderDetail() {
			try {
				const res = await this.$api.req(
					`/trade/order/get-detail`,
					{ id: this.orderId },
					'GET',
					'JSON',
					true
				);

				if (res.code === 0 && res.data) {
					this.orderInfo = res.data;
					// 找到对应的订单项
					this.orderItem = res.data.items.find(item => item.id === this.orderItemId);
					
					if (!this.orderItem) {
						uni.showToast({
							title: '订单项不存在',
							icon: 'none'
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
						return;
					}

					// 如果订单状态是待发货(10)，只能选择仅退款
					if (this.orderInfo.status === 10) {
						this.refundTypes = [
							{ label: '仅退款', value: '10', disabled: false }
						];
						this.formData.way = '10';
					}
				} else {
					uni.showToast({
						title: res.msg || '加载订单失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('加载订单详情失败:', error);
				uni.showToast({
					title: '加载订单失败',
					icon: 'none'
				});
			}
		},
		// 加载交易配置
		async loadTradeConfig() {
			try {
				const res = await this.$api.req(
					'/trade/config/get',
					{},
					'GET',
					'JSON',
					false
				);

				if (res.code === 0 && res.data) {
					this.tradeConfig = res.data;
					// 加载退款原因
					this.refundReasons = res.data.afterSaleRefundReasons || [
						'商品质量问题',
						'商品与描述不符',
						'收到商品破损',
						'发错商品',
						'不想要了',
						'其他原因'
					];
					// 加载退货原因
					this.returnReasons = res.data.afterSaleReturnReasons || [
						'商品质量问题',
						'商品与描述不符',
						'收到商品破损',
						'发错商品',
						'不想要了',
						'其他原因'
					];
					// 根据当前选择的类型设置原因列表
					this.updateReasonList();
				} else {
					// 如果加载失败，使用默认原因
					this.setDefaultReasons();
				}
			} catch (error) {
				console.error('加载交易配置失败:', error);
				// 如果加载失败，使用默认原因
				this.setDefaultReasons();
			}
		},
		// 设置默认原因
		setDefaultReasons() {
			this.refundReasons = [
				'商品质量问题',
				'商品与描述不符',
				'收到商品破损',
				'发错商品',
				'不想要了',
				'其他原因'
			];
			this.returnReasons = [
				'商品质量问题',
				'商品与描述不符',
				'收到商品破损',
				'发错商品',
				'不想要了',
				'其他原因'
			];
			this.updateReasonList();
		},
		// 更新原因列表
		updateReasonList() {
			if (this.formData.way === '10') {
				// 仅退款
				this.currentReasonList = this.refundReasons;
			} else {
				// 退款退货
				this.currentReasonList = this.returnReasons;
			}
		},
		// 申请类型改变
		onRefundTypeChange(e) {
			this.formData.way = e.detail.value;
			// 清空已选择的原因
			this.formData.applyReason = '';
			this.selectedReason = '';
			// 更新原因列表
			this.updateReasonList();
		},
		// 原因选择改变
		onReasonChange(e) {
			this.selectedReason = e.detail.value;
		},
		// 确认选择原因
		confirmReason() {
			if (!this.selectedReason) {
				uni.showToast({
					title: '请选择申请原因',
					icon: 'none'
				});
				return;
			}
			this.formData.applyReason = this.selectedReason;
			this.showReasonModal = false;
		},
		// 分转元
		fen2yuan(price) {
			return ((Number(price) || 0) / 100).toFixed(2);
		},
		// 提交退款申请
		async submitRefund() {
			// 验证表单
			if (!this.formData.way) {
				uni.showToast({
					title: '请选择申请类型',
					icon: 'none'
				});
				return;
			}

			if (!this.formData.applyReason) {
				uni.showToast({
					title: '请选择申请原因',
					icon: 'none'
				});
				return;
			}

			if (!this.orderItem) {
				uni.showToast({
					title: '订单信息错误',
					icon: 'none'
				});
				return;
			}

			uni.showModal({
				title: '确认提交',
				content: '确定要提交退款申请吗？',
				success: async (res) => {
					if (res.confirm) {
						await this.performSubmit();
					}
				}
			});
		},
		// 执行提交
		async performSubmit() {
			this.submitting = true;

			try {
				const submitData = {
					orderItemId: this.orderItemId,
					refundPrice: this.refundAmount,
					way: parseInt(this.formData.way),
					applyReason: this.formData.applyReason,
					applyDescription: this.formData.applyDescription || '',
					images: this.formData.images || []
				};

				const res = await this.$api.req(
					'/trade/after-sale/create',
					submitData,
					'POST',
					'JSON',
					true
				);

				if (res.code === 0) {
					uni.showToast({
						title: '申请成功',
						icon: 'success'
					});
					
					// 延迟跳转，让用户看到成功提示
					setTimeout(() => {
						// 跳转到售后列表页面
						uni.redirectTo({
							url: '../refundList/refundList'
						});
					}, 1500);
				} else {
					uni.showToast({
						title: res.msg || '申请失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('提交退款申请失败:', error);
				uni.showToast({
					title: '申请失败，请重试',
					icon: 'none'
				});
			} finally {
				this.submitting = false;
			}
		}
	}
};
</script>

<style>
.container {
	padding-bottom: env(safe-area-inset-bottom);
	background: #f5f5f5;
	min-height: 100vh;
}

.tui-order-item {
	margin-top: 20rpx;
	border-radius: 10rpx;
	overflow: hidden;
	background: #fff;
}

.tui-goods-title {
	width: 100%;
	font-size: 28rpx;
	font-weight: 500;
	color: #333;
}

.tui-goods-item {
	width: 100%;
	padding: 20rpx 30rpx;
	box-sizing: border-box;
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
}

.tui-goods-img {
	width: 180rpx;
	height: 180rpx;
	display: block;
	flex-shrink: 0;
	border-radius: 8rpx;
	background: #f5f5f5;
}

.tui-goods-center {
	flex: 1;
	padding: 0 20rpx;
	box-sizing: border-box;
}

.tui-goods-name {
	max-width: 100%;
	word-break: break-all;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	line-clamp: 2;
	font-size: 26rpx;
	line-height: 32rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.tui-goods-attr {
	font-size: 22rpx;
	color: #888888;
	line-height: 32rpx;
}

.tui-price-right {
	text-align: right;
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	justify-content: center;
}

.tui-price {
	font-size: 28rpx;
	color: #E41F19;
	font-weight: 500;
	margin-bottom: 10rpx;
}

.tui-count {
	font-size: 24rpx;
	color: #888888;
}

.tui-refund__form {
	margin-top: 20rpx;
	background: #fff;
	border-radius: 10rpx;
	overflow: hidden;
}

.tui-line-cell {
	width: 100%;
	padding: 24rpx 30rpx;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	min-height: 88rpx;
}

.tui-line-cell-textarea {
	align-items: flex-start;
	padding-top: 30rpx;
}

.tui-title {
	width: 180rpx;
	font-size: 28rpx;
	color: #666;
	flex-shrink: 0;
}

.tui-color__red {
	color: #EB0909;
	padding-right: 6rpx;
}

.tui-input {
	flex: 1;
	font-size: 28rpx;
	text-align: right;
}

.tui-selected-text {
	color: #333;
}

.tui-placeholder {
	color: #ccc;
}

.tui-amount-text {
	color: #E41F19;
	font-weight: 500;
	font-size: 28rpx;
}

.tui-textarea {
	width: 100%;
	min-height: 120rpx;
	font-size: 28rpx;
	color: #333;
	line-height: 1.6;
	margin-top: 10rpx;
	padding: 20rpx;
	background: #f8f8f8;
	border-radius: 8rpx;
	box-sizing: border-box;
}

.tui-radio-group {
	display: flex;
	flex: 1;
	justify-content: flex-end;
	gap: 40rpx;
}

.tui-radio-item {
	display: flex;
	align-items: center;
}

.tui-radio-text {
	font-size: 28rpx;
	color: #333;
	margin-left: 10rpx;
}

.tui-btn__box {
	padding: 60rpx 30rpx;
	background: #fff;
	margin-top: 20rpx;
}

/* 弹窗样式 */
.tui-modal-box {
	background: #fff;
	border-radius: 20rpx 20rpx 0 0;
	max-height: 80vh;
	overflow: hidden;
	display: flex;
	flex-direction: column;
}

.tui-modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.tui-modal-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.tui-modal-close {
	font-size: 40rpx;
	color: #999;
	line-height: 1;
	width: 40rpx;
	height: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.tui-modal-content {
	flex: 1;
	overflow-y: auto;
	padding: 20rpx 0;
	max-height: 60vh;
}

.tui-reason-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 25rpx 30rpx;
	border-bottom: 1rpx solid #f5f5f5;
}

.tui-reason-item:last-child {
	border-bottom: none;
}

.tui-reason-text {
	font-size: 28rpx;
	color: #333;
	flex: 1;
}

.tui-modal-footer {
	display: flex;
	justify-content: space-around;
	padding: 30rpx;
	border-top: 1rpx solid #f0f0f0;
	background: #fff;
}
</style>
